import json
import math
import os

from PyQt5.QtCore import QThread, pyqtSignal, QMutex

from mypackage.views.MyWindow import Title

from PyQt5.QtWidgets import QApplication, QFileDialog
from .qrGenerate import QRCodeGenerator

import sys
import ctypes


class Win():
    def __init__(self, parent=None, *args, **kwargs):
        '''
        构造函数，初始化对象
        :param parent: 父对象
        :param args: 可变参数
        :param kwargs: 关键字参数
        '''
        self.ui = Title()  # 创建Title对象并赋值给self.ui
        self.size = '10'  # 设置self.size为字符串'10'
        self.initUi()  # 调用initUi方法

    def initUi(self):
        # 初始化用户界面
        self.ui.lineEdit_2.setText(self.size)  # 将self.size的值设置给self.ui的lineEdit_2文本框
        # 当点击pull_map按钮时，连接到openmap方法
        self.ui.pull_map.clicked.connect(self.openmap)
        # 当文本框中的文本内容改变时，调用change_size方法
        self.ui.lineEdit_2.textChanged.connect(lambda text: self.change_size(text))
        # 当点击push_qr按钮时，调用open_file方法
        self.ui.push_qr.clicked.connect(self.open_file)


    def openmap(self):
        try:
            openfile_name = QFileDialog.getOpenFileName(None, '选择文件', './', 'All types (*.*)')
            if openfile_name[0] == '':
                return
            else:
                openfile_name = openfile_name[0]
                print(openfile_name)
                # print(openfile_name)
                # openfile_name_dir = openfile_name[:openfile_name.rfind('/')]
                self.ui.lineEdit.setText(os.path.basename(openfile_name))
                self.openmap = OpenMap(openfile_name)
                self.openmap.mes.connect(self.position)
                # self.openmap.run()
                self.openmap.mutex.lock()
                if not self.openmap.running:
                    self.openmap.start()
                self.openmap.mutex.unlock()

        except Exception as e:
            print(f"Error opening{e}")

    def position(self, data):
        if isinstance(data[0], str):
            print(data)
        else:
            self.pos = data
            # print(self.position)

    def change_size(self, text):
        self.size = text
        # print(self.size)

    def open_file(self):
        openfile_name = QFileDialog.getExistingDirectory(None, "选择存储文件夹", os.getcwd())
        if openfile_name == '':
            return
        else:
            self.size = self.ui.lineEdit_2.text()
            self.qrgenerate = QR_GEN(filedir=openfile_name, size=int(self.size), position=self.pos)
            self.qrgenerate.progress_value.connect(self.start_qr)
            self.qrgenerate.mutex.lock()
            if not self.qrgenerate.running:
                self.qrgenerate.start()
            self.qrgenerate.mutex.unlock()

    def start_qr(self, value):
        self.ui.progressBar.setValue(value)
        # print(f"value_mes:{value}")

    def show(self):
        self.ui.show()


class OpenMap(QThread):
    mes = pyqtSignal(list)

    def __init__(self, load, parent=None):
        super(OpenMap, self).__init__(parent)
        self.load = load
        self.position = []
        self.mutex = QMutex()
        self.running = False

    def run(self):
        try:
            self.mutex.lock()
            self.running = True
            self.mutex.unlock()
            if self.load[-4:] == 'mooe':
                with open(self.load, 'r', encoding='utf-8') as fr:
                    mLaneMarks = json.load(fr).get('mLaneMarks', [])
                for i in mLaneMarks:
                    mLaneMarksName = i.get('mLaneMarkName', '-1')
                    mlaneMarkType = i.get('mLaneMarkType', '-1')
                    mLaneMarkID = i.get('mLaneMarkID', '-1')
                    if mLaneMarksName == '':
                        continue
                    if mlaneMarkType in [11, 2] and mLaneMarksName[-1] not in ['点', '检', '别']:
                        self.position.append({"mLaneMarkName": mLaneMarksName, "mLaneMarkID": mLaneMarkID})
                        # print(self.position)
                if self.position:
                    self.mes.emit(self.position)
                else:
                    self.mes.emit(["文件为空"])
            else:
                self.mes.emit(["文件格式错误"])
            self.mutex.lock()
            self.running = False
            self.mutex.unlock()
        except Exception as e:
            print(f"文件解析失败{e}")
            self.mes.emit(["文件解析失败"])


class QR_GEN(QThread):
    progress_value = pyqtSignal(int)

    def __init__(self, filedir='./', size=10, position='', parent=None):
        super(QThread, self).__init__(parent)
        self.filedir = filedir
        self.size = size
        self.position = position
        self.mutex = QMutex()
        self.running = False

    def run(self):
        try:
            self.mutex.lock()
            self.running = True
            self.mutex.unlock()
            self.qrgenerator = QRCodeGenerator(box_size=self.size)
            for index, pos in enumerate(self.position, start=1):
                pos_id = pos.get('mLaneMarkID', '')
                pos_name = pos.get('mLaneMarkName', '')
                self.qrgenerator.set_data(bottom=pos_name, left=str(pos_id))
                save_path = os.path.join(self.filedir, f'{pos_id}.png')
                self.qrgenerator.save_qr_code(save_path)
                from barcode import Code128
                from barcode.writer import ImageWriter
                # 创建条形码对象
                code = Code128(str(pos_id), writer=ImageWriter())
                # 将条形码保存为 PNG 文件
                filename = code.save(os.path.join(self.filedir, pos_name))
                value = index / (len(self.position) + 1) * 100
                # if self.is_integer_division(index * 100, len(self.position) + 1):
                # print(f"value={value}")
                self.progress_value.emit(math.ceil(value))
                if index == len(self.position):
                    self.progress_value.emit(100)
            self.mutex.lock()
            self.running = True
            self.mutex.unlock()
        except Exception as e:
            print(f"Error generating{e}")

    def is_integer_division(self, a, b):
        return a % b == 0


if __name__ == '__main__':
    # 设置任务栏图标
    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
    # 适配2k等高分辨率屏幕,低分辨率屏幕可以缺省
    # QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    win = Win()
    win.show()
    sys.exit(app.exec_())
